package com.huaxiafinance.management.service.impl;


import com.huaxiafinance.management.constant.CommonConstant;
import com.huaxiafinance.management.dto.request.AddScoreProDto;
import com.huaxiafinance.management.dto.request.QueryShoppingProDto;
import com.huaxiafinance.management.dto.response.QueryScoreProDto;
import com.huaxiafinance.management.mapper.MallProductMapper;
import com.huaxiafinance.management.mapper.MallRecommendMapper;
import com.huaxiafinance.management.mapper.MallSupplierMapper;
import com.huaxiafinance.management.mapper.ProductSkuMapper;
import com.huaxiafinance.management.model.*;
import com.huaxiafinance.management.service.YfqShoppingProService;
import com.huaxiafinance.management.util.DateUtil;
import com.huaxiafinance.management.util.ReflexUtil;
import com.huaxiafinance.management.util.UUIDUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;

/**
 * Created by xieWei on 2017/9/4.
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Service("yfqShoppingProService")
@Transactional
public class YfqShoppingProServiceImpl implements YfqShoppingProService {
    private static final Logger log = Logger.getLogger(YfqShoppingProServiceImpl.class);
    @Autowired
    private MallProductMapper mallProductMapper;
    @Autowired
    private MallRecommendMapper mallRecommendMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private MallSupplierMapper mallSupplierMapper;
    /**
     *商品列表
     */
    @Override
    public List<Map> queryList(QueryShoppingProDto dto) {
        if (dto.getRows()==null||dto.getPage()==null){
            dto.setPage(0);
            dto.setRows(20);
        }else {
            dto.setPage(dto.getPage() * dto.getRows());
        }
        return mallProductMapper.selectList(dto);
    }
    /**
     *商品列表统计
     */
    @Override
    public int countList(QueryShoppingProDto dto) {
        return mallProductMapper.countList(dto);
    }

    /**
     *存推荐位商品
     */
    @Override
    @Transactional
    public void putRec(List<MallRecommend> recommend) {
        mallRecommendMapper.deletAll();
        int i=1;
        for (MallRecommend rc:recommend){
            if(rc.getProName()==null || "".equals(rc.getProName())){
                rc.setProCode(null);
            }
            rc.setRecommendPosition(i);
            mallRecommendMapper.insertSelective(rc);
            //推荐位加一
            i=i+1;
        }
    }
    /**
    *查询商品通过code
    */
    @Override
    public MallProduct queryByCode(String code) {

        return  mallProductMapper.queryByCode(code);
    }
    /**
    *推荐位列表
    */
    @Override
    public List<MallRecommend> selectAll() {
        return mallRecommendMapper.selectAll();
    }

    /**
     * 添加商品
     * @param dto
     * @return 1 成功 2 参数不能少于两条 3 规格不能为空 4 价格不能为空 5 商品名字重复 6 sku最少一个
     *
     */
    @Override
    @Transactional
    public synchronized int addPro(AddScoreProDto dto) throws Exception {
        String proName=dto.getInfo().getProName();
        List nameList= mallProductMapper.selectProNameList();
        if(nameList.contains(proName)){
            return 5;
        }

        String uuid= UUIDUtil.getUUID();
        MallProduct info=dto.getInfo();
        String code=mallProductMapper.selectProCode();
        if(code ==null){
            info.setProCode("00001");
        }else {
            int i=Integer.parseInt(code);
            NumberFormat nf = NumberFormat.getInstance();
            nf.setGroupingUsed(false);
            //设置最大整数位数
            nf.setMaximumIntegerDigits(5);
            //设置最小整数位数
            nf.setMinimumIntegerDigits(5);
            //code加1
            info.setProCode(nf.format(i+1));
        }
        info.setProUuid(uuid);
        info.setGmtCreate(new Date());
        int category=info.getProType();
        List<ProductSku> r=new ArrayList<>();
        int ii=0;
        int y=0;
        //判断规格
        for(ProductSku sku:dto.getSku()){
            //判断sku最少一个完整的
            if(sku.getPriceType()==1){
                if (sku.getSpecOne()!=null
                        &&sku.getScore()!=null
                        &&sku.getStock()!=null
                        &&sku.getMarkPrice()!=null){
                    if(sku.getDisplayPrice()==1){
                        y=1;
                    }
                    sku.setPrice(new BigDecimal(0));
                    r.add(sku);
                    ii=1;

                }
            }else if (sku.getPriceType()==2){
                if (sku.getSpecOne()!=null
                        &&sku.getScore()!=null
                        &&sku.getStock()!=null
                        &&sku.getMarkPrice()!=null
                        &&sku.getPrice()!=null){
                    if(sku.getDisplayPrice()==1){
                        y=1;
                    }
                    r.add(sku);
                    ii=1;
                }
            }
        }
        if (ii==0){
            return 6;
        }
        //默认第一个被选中
        if(y==0){
            r.get(0).setDisplayPrice(1);
        }
        switch (category){
            case CommonConstant.mzhf:
                //美妆护肤
                MzhfProductParam mzfu=dto.getParameter();
                if(!ReflexUtil.chooseBean(mzfu,2)){
                    return 2;
                }
                if(mzfu.getDateOfManufacture()!=null){
                    mzfu.setGmtProduce(DateUtil.stringToDate("yyyy/MM/dd",mzfu.getDateOfManufacture()));
                }
                mzfu.setProUuid(uuid);
                mzfu.setGmtCreate(new Date());
                mallProductMapper.insertMzhfSelective(mzfu);
                break;
            case CommonConstant.sjsm:
                //手机数码
                SjsmProductParam sjsm=dto.getSjsmPro();
                if(!ReflexUtil.chooseBean(sjsm,2)){
                    //2代表商品参数不够两个
                 return 2;
                }
                if(sjsm.getMarketDate()!=null ){
                    //日期格式转化
                    sjsm.setGmtMarket(DateUtil.stringToDate("yyyy/MM/dd",sjsm.getMarketDate()));
                }
                sjsm.setProUuid(uuid);
                sjsm.setGmtCreate(new Date());
                mallProductMapper.insertSjsmSelective(sjsm);
                break;
            case CommonConstant.ssqs:
                //时尚轻奢护肤
                SsqsProductParam ssqs=dto.getSsqsPro();
                if(!ReflexUtil.chooseBean(ssqs,2)){
                    return 2;
                }
                ssqs.setProUuid(uuid);
                ssqs.setGmtCreate(new Date());
                mallProductMapper.insertSsqsSelective(ssqs);
                break;
            case CommonConstant.jkys:
                //健康养生
                JkysProductParam jkys=dto.getJkysPro();
                if(!ReflexUtil.chooseBean(jkys,2)){
                    return 2;
                }
                if(jkys.getProduceDate()!=null){
                    jkys.setGmtProduce(DateUtil.stringToDate("yyyy/MM/dd",jkys.getProduceDate()));
                }
                jkys.setProUuid(uuid);
                jkys.setGmtCreate(new Date());
                mallProductMapper.insertJkysSelective(jkys);
                break;
                default:
                    break;
        }
        //sku信息插入
        for(ProductSku sku:r){
            if(sku.getPriceType()==1){
                if (sku.getSpecOne()!=null
                        &&sku.getScore()!=null
                        &&sku.getStock()!=null
                        &&sku.getMarkPrice()!=null){
                    sku.setProUuid(uuid);
                    sku.setGmtCreate(new Date());
                    productSkuMapper.insertSelective(sku);
                }

            }else if (sku.getPriceType()==2){
                if (sku.getSpecOne()!=null
                        &&sku.getScore()!=null
                        &&sku.getStock()!=null
                        &&sku.getMarkPrice()!=null
                        &&sku.getPrice()!=null){
                    sku.setProUuid(uuid);
                    sku.setGmtCreate(new Date());
                    productSkuMapper.insertSelective(sku);
                }
            }
        }
        //插入放后面保证前面的判断完后
        mallProductMapper.insertSelective(info);
        //普通图片
        for(MallProductImg img:dto.getImgList()){
            if(img!=null){
                img.setProUuid(uuid);
                img.setGmtCreate(new Date());
                mallProductMapper.insertProImgSelective(img);
            }
        }
        //介绍图片
        for(MallProductImg img:dto.getIntroduceImg()){
            if(img!=null){
                img.setProUuid(uuid);
                img.setGmtCreate(new Date());
                mallProductMapper.insertProImgSelective(img);
            }
        }
        return 1;
    }
    /**
     *查询标签列表
     */
    @Override
    public List<Map> selectTag(Integer category) {
        return mallProductMapper.selectTag(category);
    }

    /**
     * 商品详情
     * @param id 商品id
     * @return
     */
    @Override
    public QueryScoreProDto getProOne(Integer id) {
        QueryScoreProDto queryScoreProDto =new QueryScoreProDto();
        MallProduct product=mallProductMapper.selectPro(id);
        if(product==null){
            return null;
        }
        String supplierName=null;
        MallSupplier mallSupplier=mallSupplierMapper.selectByPrimaryKey(product.getSupplierId());
        if(mallSupplier!=null){
            supplierName=mallSupplier.getSupplierName();
        }
        product.setSupplierName(supplierName);
        queryScoreProDto.setInfo(product);
        int status=product.getProOnshelfStatus();
        String uuid=product.getProUuid();
        String proCode=product.getProCode();
        Integer actualSales=product.getProActualSales();
        Integer baseSales=product.getProBaseSales();
        product.setProSales((actualSales==null?0:actualSales)+(baseSales==null?0:baseSales));
        switch (product.getProType()){
            case CommonConstant.mzhf:
                //美妆护肤
                MzhfProductParam mzhf=mallProductMapper.selectMzhfOne(uuid);
                if(mzhf.getGmtProduce()!=null){
                    mzhf.setDateOfManufacture(DateUtil.formatDate(mzhf.getGmtProduce(),"yyyy/MM/dd"));
                }
                queryScoreProDto.setParameter(mzhf);
                break;
            case CommonConstant.sjsm:
                //手机数码
                SjsmProductParam sjsm=mallProductMapper.selectSjsmOne(uuid);
                if(sjsm.getGmtMarket()!=null){
                    sjsm.setMarketDate(DateUtil.formatDate(sjsm.getGmtMarket(),"yyyy/MM/dd"));
                }
                queryScoreProDto.setSjsmPro(sjsm);
                break;
            case CommonConstant.ssqs:
                //时尚轻奢护肤
                queryScoreProDto.setSsqsPro(mallProductMapper.selectSsqsOne(uuid));
                break;
            case CommonConstant.jkys:
                //健康养生
                JkysProductParam jkys=mallProductMapper.selectJkysOne(uuid);
                if(jkys.getGmtProduce()!=null){
                    jkys.setProduceDate(DateUtil.formatDate(jkys.getGmtProduce(),"yyyy/MM/dd"));
                }
                queryScoreProDto.setJkysPro(jkys);
                break;
                default:
                    break;
        }
        queryScoreProDto.setSku(mallProductMapper.selectSkuList(uuid));
        List<ProductSku> list=mallProductMapper.selectSkuList(uuid);
        ProductSku sku1=list.get(0);
        int priceType=0;
        BigDecimal shippingExpense=null;
        if(sku1!=null){
            priceType=sku1.getPriceType();
            shippingExpense=sku1.getShippingExpense();
        }
        //规格一集合
        LinkedHashSet set1=new LinkedHashSet();
        //规格二集合
        LinkedHashSet set2=new LinkedHashSet();
        //规格三集合
        LinkedHashSet set3=new LinkedHashSet();
        for(ProductSku sku:list){
           set1.add(sku.getSpecOne());
           set2.add(sku.getSpecTwo());
           set3.add(sku.getSpecThree());
        }
        if(status==1){
            Integer r=mallProductMapper.selectRecByCode(proCode);
            if(r!=null){
                queryScoreProDto.setIndexRecommend(r);
            }
        }
        queryScoreProDto.setPriceType(priceType);
        queryScoreProDto.setShippingExpense(shippingExpense);
        queryScoreProDto.setOne(set1);
        queryScoreProDto.setThree(set3);
        queryScoreProDto.setTwo(set2);
        queryScoreProDto.setIntroduceImg(mallProductMapper.selectIntroduceImg(uuid));
        queryScoreProDto.setImgList(mallProductMapper.CommodityImg(uuid));
        return queryScoreProDto;
    }

    /**
     * 编辑商品
     * @param dto
     * @return   1 成功 2 参数不能少于两条 3 规格不能为空 4 价格不能为空 5 商品名字重复 6 sku最少一个
     * @throws Exception
     */
    @Override
    @Transactional
    public synchronized int updatePro(AddScoreProDto dto) throws Exception {
        MallProduct pro=mallProductMapper.selectByPrimaryKey(dto.getInfo().getId());
        String oldName=pro.getProName();
        if(!oldName.equals(dto.getInfo().getProName())){
            if(mallProductMapper.selectProNameList().contains(dto.getInfo().getProName())){
                //名字重复
                return 7;
            }
        }
        int type=dto.getInfo().getProType();
        String uuid=dto.getInfo().getProUuid();
        int ii=0;
        int j=0;
        List<ProductSku> l=new ArrayList<>();
        //判断sku最少一个完整的
        for(ProductSku sku:dto.getSku()){
            //判断sku最少一个完整的
            if(sku.getPriceType()==1){
                if (sku.getSpecOne()!=null
                        &&sku.getScore()!=null
                        &&sku.getStock()!=null
                        &&sku.getMarkPrice()!=null){
                    sku.setPrice(new BigDecimal(0));
                    l.add(sku);
                    if(sku.getDisplayPrice()==1){
                        j=1;
                    }
                    ii=1;

                }
            }else if (sku.getPriceType()==2){
                if (sku.getSpecOne()!=null
                        &&sku.getScore()!=null
                        &&sku.getStock()!=null
                        &&sku.getMarkPrice()!=null
                        &&sku.getPrice()!=null){
                    l.add(sku);
                    if(sku.getDisplayPrice()==1){
                        j=1;
                    }
                    ii=1;
                }
            }
        }
        if (ii==0){
            return 8;
        }
        if(j==0){
            l.get(0).setDisplayPrice(1);
        }
        switch (type){
            case CommonConstant.mzhf:
                //美妆护肤
                MzhfProductParam mzfu=dto.getParameter();
                if(!ReflexUtil.chooseBean(mzfu,3)){
                    return 2;
                }
                if(mzfu.getDateOfManufacture()!=null){
                    mzfu.setGmtProduce(DateUtil.stringToDate("yyyy/MM/dd",mzfu.getDateOfManufacture()));
                }
                mallProductMapper.updateMzfhByPrimaryKeySelective(mzfu);
                break;
            case CommonConstant.sjsm:
                //手机数码
                SjsmProductParam sjsm=dto.getSjsmPro();
                if(!ReflexUtil.chooseBean(sjsm,3)){
                    //2代表商品参数不够两个
                    return 2;
                }
                if(sjsm.getMarketDate()!=null ){
                    //日期格式转化
                    sjsm.setGmtMarket(DateUtil.stringToDate("yyyy/MM/dd",sjsm.getMarketDate()));
                }
                mallProductMapper.updateSjsmByPrimaryKeySelective(sjsm);
                break;
            case CommonConstant.ssqs:
                //时尚轻奢护肤
                SsqsProductParam ssqs=dto.getSsqsPro();
                if(!ReflexUtil.chooseBean(ssqs,3)){
                    return 2;
                }
                mallProductMapper.updateSsqsByPrimaryKeySelective(ssqs);
                break;
            case CommonConstant.jkys:
                //健康养生
                JkysProductParam jkys=dto.getJkysPro();
                if(!ReflexUtil.chooseBean(jkys,3)){
                    return 2;
                }
                if(jkys.getProduceDate()!=null){
                    jkys.setGmtProduce(DateUtil.stringToDate("yyyy/MM/dd",jkys.getProduceDate()));
                }
                mallProductMapper.updateJkysByPrimaryKeySelective(jkys);
                break;
            default:
                break;
        }
        mallProductMapper.updateByPrimaryKeySelective(dto.getInfo());
        mallProductMapper.deleteImg(uuid);
        //普通图片
        for(MallProductImg img:dto.getImgList()){
            if(img!=null){
                img.setId(null);
                img.setProUuid(uuid);
                mallProductMapper.insertProImgSelective(img);
            }
        }
        //介绍图片
        for(MallProductImg img:dto.getIntroduceImg()){
            if(img!=null){
                img.setId(null);
                img.setProUuid(uuid);
                mallProductMapper.insertProImgSelective(img);
            }
        }
        //数据库已有id
        List<Integer> list1=mallProductMapper.selectIdOfSku(uuid);
        //前端发给我的id
        List<Integer> list2=new ArrayList<>();
        for(ProductSku sku:l){
            //包含就改没有就新加
            if(list1.contains(sku.getId())){
                //修改
                if (sku.getPriceType()==1){
                    if (sku.getSpecOne() != null
                            && sku.getScore() != null
                            && sku.getStock() != null
                            && sku.getMarkPrice() != null){
                            productSkuMapper.updateByPrimaryKeySku(sku);
                    }else {
                        productSkuMapper.deleteByPrimaryKey(sku.getId());
                    }
                }else if (sku.getPriceType()==2){
                    if (sku.getSpecOne() != null
                            && sku.getScore() != null
                            && sku.getStock() != null
                            && sku.getMarkPrice() != null
                            &&sku.getPrice()!=null){
                            productSkuMapper.updateByPrimaryKeySku(sku);
                    }else {
                        productSkuMapper.deleteByPrimaryKey(sku.getId());
                    }
                }

            }else {
                //判断sku增加
                if(sku.getPriceType()==1) {
                    if (sku.getSpecOne() != null
                            && sku.getScore() != null
                            && sku.getStock() != null
                            && sku.getMarkPrice() != null) {
                        sku.setProUuid(uuid);
                        sku.setGmtCreate(new Date());
                         productSkuMapper.insertSelective(sku);
                    }
                }else if (sku.getPriceType()==2){
                    if (sku.getSpecOne()!=null
                            &&sku.getScore()!=null
                            &&sku.getStock()!=null
                            &&sku.getMarkPrice()!=null
                            &&sku.getPrice()!=null){
                        sku.setProUuid(uuid);
                        sku.setGmtCreate(new Date());
                         productSkuMapper.insertSelective(sku);
                    }
                }
            }
            if(sku.getId()!=null){
                list2.add(sku.getId());
            }
        }


        list1.removeAll(list2);
        for(Integer id:list1){
            if(id!=null){
                productSkuMapper.deleteByPrimaryKey(id);
            }
        }
        return 1;
    }

    /**
     * 逻辑删除商品
     * @param id 商品的id
     */
    @Override
    public void deletePro(Integer id) {
        MallProduct mallProduct=new MallProduct();
        mallProduct.setId(id);
        //1 表示删除 0 表示可以
        mallProduct.setIsDeleted(1);
        mallProductMapper.updateByPrimaryKeySelective(mallProduct);
    }

    /**
    *上下架
    */
    @Override
    public int upDown(int id,int isGround) {
        MallProduct mallProduct=new MallProduct();
        mallProduct.setId(id);
        mallProduct.setProOnshelfStatus(isGround);
        if(isGround==1){
            mallProduct.setGmtOnshelf(new Date());
        }
        int a=0;
        try {
            a=mallProductMapper.updateByPrimaryKeySelective(mallProduct);
        }catch (Exception e){
            log.error("系统异常",e);
        }
        return a;
    }
   /**
   *类别列表
   */
    @Override
    public List<Map> selectType() {
        return mallProductMapper.selectType();
    }

}
